package edu.java.ishop.socketserver;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.List;
import java.util.concurrent.Semaphore;

import edu.java.ishop.dao.ProductDao;
import edu.java.ishop.dao.impl.ProductFileDao;
import edu.java.ishop.model.Product;
import edu.java.ishop.utils.ApplicationConfiguration;

public class ProductSocketServer {
	private static ProductSocketServer instance = new ProductSocketServer();
	private boolean stopMe = false;
	private ProductSocketServer() {
		// TODO Auto-generated constructor stub
	}
	public static void launch(Semaphore startCallback) throws IOException{
		instance.start(startCallback);
	}
	private void start(Semaphore startCallback) throws IOException {
		ProductDao dao = new ProductFileDao();
		
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); 
		
		final Integer port = Integer.valueOf(ApplicationConfiguration.getItem("socket.server.port"));
		
		serverSocketChannel.socket().bind(new InetSocketAddress(port));
		serverSocketChannel.configureBlocking(false);
		
		startCallback.release();
		
		while(!stopMe){
			
			final SocketChannel socketChannel = serverSocketChannel.accept();
			
			if(socketChannel == null){
				continue;
			}
			Socket socket = socketChannel.socket();
			ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
			objectOutputStream.flush();
			
			final BufferedReader requestReader = new BufferedReader(  
					new InputStreamReader( socket.getInputStream()));
			String command = requestReader.readLine();
			if (command != null){
				switch (command) {
				case "getAll":
					//write product list to output stream
					final List<Product> products = dao.getAll();
					objectOutputStream.writeObject(products);
				break;
				default:
					break;
				}
			}
			
			requestReader.close();
			socket.close();
		}
		
		serverSocketChannel.close();
		stopMe = false;		
	}
	public static void shutdown(){
		instance.stopMe = true;
	}
}
